const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.post('/update-news', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const {
    id,
    title,
    classid,
    news_type,
    intro,
    cover,
    status,
    content,
    tags,
    files,
    img,
  } = req.body
  if (
    !Bee.StringUtils.isNotBlank(title) ||
    !Bee.StringUtils.isNotBlank(intro) ||
    !Bee.StringUtils.isNotBlank(content) ||
    !Bee.StringUtils.isNumber(id) ||
    !Bee.StringUtils.isNumber(classid) ||
    !Bee.StringUtils.isNumber(news_type) ||
    !Bee.StringUtils.isNumber(status)
  )
    return handleError(10003, '参数错误')

  const [findNewsError, findNews] = await to(
    db.query('SELECT count(*) FROM news WHERE id = ?', [id])
  )
  if (findNewsError || !findNews) return handleError(-1, findNewsError)
  let total = findNews[0]['count(*)']
  if (total === 0) return handleError(-1, '系统错误')

  const [updateNewsError, updateNewsSuccess] = await to(
    db.query(
      'UPDATE news SET title=?, classid=?, updated_time=NOW(), news_type=?, intro=?, cover=?, status=?, content=?, tags=?, files=?, img=? WHERE id = ?',
      [
        title,
        classid,
        news_type,
        intro,
        cover ? cover : '',
        status,
        content,
        tags ? tags : '',
        files ? files : '',
        img ? img : '',
        id,
      ]
    )
  )
  if (updateNewsError || !updateNewsSuccess)
    return handleError(-1, updateNewsError)

  return resp.json({
    code: 0,
    msg: status_code[0],
    data: {
      id,
    },
  })
})

module.exports = router
